package com.lx.apk.encrypt;

import com.lx.apk.encrypt.utils.DxUtils;
import com.lx.apk.encrypt.utils.EncryptUtils;
import com.lx.apk.encrypt.utils.FileUtils;
import com.lx.apk.encrypt.utils.LogUtils;
import com.lx.apk.encrypt.utils.SignUtils;
import com.lx.apk.encrypt.utils.ZipUtils;

import java.io.File;

public class ApkEncryptMain {
    private static final String SOURCE_APK_PATH = "Encrypt/source/apk/app-debug.apk";
    private static final String SHUCK_APK_PATH = "Encrypt/source/arr/ApkShuck-release.aar";

    public static void main(String[] args) {
        LogUtils.i("start encrypt");
        init();
        /**
         * 1. 解压源apk文件到 ../source/apk/temp目录下，并加密dex文件
         */
        File sourceApk = new File(SOURCE_APK_PATH);
        File newApkDir = new File(sourceApk.getParent() + File.separator + "temp");
        if (!newApkDir.exists()) {
            newApkDir.mkdirs();
        }
        // 解压Apk并加密dex文件
        EncryptUtils.getInstance().encryptApkFile(sourceApk, newApkDir);

        /**
         * 2. 解压arr文件（不能进行加密的部分），将其中的dex文件拷贝到apk/temp目录中。
         */
        File shuckApk = new File(SHUCK_APK_PATH);
        File newShuckDir = new File(shuckApk.getParent() + File.separator + "temp");
        if (!newShuckDir.exists()) {
            newShuckDir.mkdirs();
        }
        // 解压arr文件，并将arr中的jar文件转化为dex文件, 最后拷贝arr中的classes.dex 到 apk/temp 目录中
        DxUtils.jar2Dex(shuckApk, newShuckDir);

        /**
         * 3. 打包apk/temp目录生成新的未签名的apk文件
         */
        File unsignedApk = new File("Encrypt/result/apk-unsigned.apk");
        unsignedApk.getParentFile().mkdirs();
        unsignedApk.delete();
        ZipUtils.zip(newApkDir, unsignedApk);

        /**
         * 4. 对齐
         */
        File unAlignApk = new File("Encrypt/result/apk-unAlign.apk");
        unAlignApk.getParentFile().mkdirs();
        unAlignApk.delete();
        ZipUtils.zipalign(unsignedApk, unAlignApk);

        /**
         * 5 .给新apk添加签名,生成签名apk
         */
        File signedApk = new File("Encrypt/result/apk-signed.apk");
        signedApk.getParentFile().mkdirs();
        signedApk.delete();
        SignUtils.signature(unAlignApk, signedApk);
    }

    /**
     * 初始化
     */
    private static void init() {
        // 删除缓存
        FileUtils.delFolder(new File("Encrypt/source/apk/temp"));
        FileUtils.delFolder(new File("Encrypt/source/arr/temp"));
    }
}